<?php

namespace App\Http\Controllers\Api\V1;

use App\B2BProject\Custom\Purchaser\ValueAddedTaxInvoiceQualification;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Validator;
use Auth;

class VATInvoiceController extends Controller
{
    public function getIndex()
    {
        if ($VAT = Auth::user()->VAT) {
            return success_return([
                'company_name'     => $VAT->company_name,
                'code'             => $VAT->code,
                'address'          => $VAT->address,
                'phone'            => $VAT->phone,
                'bank'             => $VAT->bank,
                'bank_account'     => $VAT->bank_account,
                'bill_to_name'     => $VAT->bill_to_name,
                'bill_to_address'  => $VAT->bill_to_address,
                'bill_to_province' => $VAT->bill_to_province,
                'bill_to_phone'    => $VAT->bill_to_phone,
            ]);
        }

        return success_return(null);
    }

    public function putIndex(Request $request)
    {
        $validator = Validator::make($request->all(), [
            'company_name'     => 'required',
            'code'             => 'required',
            'address'          => 'required',
            'phone'            => 'required',
            'bank'             => 'required',
            'bank_account'     => 'required',
            'bill_to_name'     => 'required',
            'bill_to_address'  => 'required',
            'bill_to_province' => 'required',
            'bill_to_phone'    => 'required',
        ]);

        if ($validator->fails()) {
            return error_return(900004, 403);
        }

        $attributes = $request->only([
            'company_name',
            'code',
            'address',
            'phone',
            'bank',
            'bank_account',
            'bill_to_name',
            'bill_to_address',
            'bill_to_province',
            'bill_to_phone',
        ]);

        if ($VAT = Auth::user()->VAT) {
            foreach ($attributes as $attribute => $value) {
                $VAT->$attribute = $value;
            }

            $VAT->save();
        } else {
            $VAT = new ValueAddedTaxInvoiceQualification();
            foreach ($attributes as $attribute => $value) {
                $VAT->$attribute = $value;
            }

            $VAT->member_id = Auth::id();

            $VAT->save();
            Auth::user()->VAT()->save($VAT);
        }

        return success_return(null);
    }
}
